﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using System.Data.Common;


namespace GgCarControl
{
    public partial class DISPATCH_ST : DockContent
    {
        private class Item
        {
            public string Name;
            public int Value;
            public Item(string name, int value)
            {
                Name = name; Value = value;
            }
            public override string ToString()
            {
                return Name;
            }
        }
        
        public DISPATCH_ST()
        {
            InitializeComponent();
        }

        //定义自动刷新的delegate
        delegate void DataGridTruckLoginHandler(DataTable dt);
        event DataGridTruckLoginHandler TruckLogin;

        public static Database db =
             new OracleDatabase("Data Source=DG;User ID=dgrfid;Password=dgrfid;Unicode=True;Load Balance Timeout=1000");
        DataTable dt;

        private void button1_Click(object sender, EventArgs e)
        {
            if (Session.QX == "0")
            {
                OrderSendCommand();
            }
            else
            {
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    object obj = this.dataGridView1.Rows[i].Cells[0].Value;
                    string select = obj == null ? "" : obj.ToString();
                    if (select == "True")
                    {
                        string car_no = this.dataGridView1.Rows[i].Cells["车号"].Value.ToString();
                        string login_time = this.dataGridView1.Rows[i].Cells["登记时间"].Value.ToString();
                        //String update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=1,COMMANDTIME=sysdate  where IOYARDID='" + ioyarid + "' and TRUCKNO='" + car_no + "'";
                        String update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=1,COMMANDTIME=sysdate where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS<>'9'";
                        db.ExecuteNonQuery(db.GetSqlStringCommand(update_sql.ToString()));
                        string sID = create_id();
                        string insert_sql = "insert into TRUCK_COMMAND_LOG(ID,TRUCKNO,YHBH,XM,XGSJ,XGNR,IOYARDID,SXFC,MODULE,SEND) " +
                            "values(" + sID + ",'" + car_no + "','" + Session.YHBH + "','" + Session.XM + "',sysdate,'理货中心发送进车指令','0','0','市提车辆调度','1')";
                        db.ExecuteNonQuery(db.GetSqlStringCommand(insert_sql));
                    }
                }
            }
            load_data();
        }

        /// <summary>
        /// 顺序发送放车指令
        /// </summary>
        private void OrderSendCommand()
        {
            DataTable sortTable = GetSelectedRowsSortTable();
            if (sortTable.Rows.Count > 0)
            {
                //发送放车指令
                foreach (DataRow row in sortTable.Rows)
                {
                    string stackname = row["stackName"].ToString();
                    string sWhere = string.IsNullOrEmpty(stackname) ? "stackname is null" : "stackname='" + stackname + "'";

                    string pack = row["package"].ToString();
                    sWhere += string.IsNullOrEmpty(pack) ? " and package is null" : " and package='" + pack + "'";

                    string login_time = row["loginTime"].ToString();
                    string sql = "select id from truck_cargo_login where TRUCKSTATUS='0' and ioyardid=0 and " + sWhere + " and logintime<to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss')";
                    DataTable dtResult = db.ExecuteDataSet(db.GetSqlStringCommand(sql)).Tables[0];
                    if (dtResult != null && dtResult.Rows.Count > 0)
                    {
                        MessageBox.Show("请按照垛名、包装形式、登记时间顺序放车！");
                        return;
                    }
                    string car_no = row["truckNo"].ToString();
                    String update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=1,COMMANDTIME=sysdate where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS<>'9'";
                    db.ExecuteNonQuery(db.GetSqlStringCommand(update_sql.ToString()));
                    string sID = create_id();
                    string insert_sql = "insert into TRUCK_COMMAND_LOG(ID,TRUCKNO,YHBH,XM,XGSJ,XGNR,IOYARDID,SXFC,MODULE,SEND) " +
                        "values(" + sID + ",'" + car_no + "','" + Session.YHBH + "','" + Session.XM + "',sysdate,'理货中心发送进车指令','0','1','市提车辆调度','1')";
                    db.ExecuteNonQuery(db.GetSqlStringCommand(insert_sql));
                }
            }
        }

        private DataTable GetSelectedRowsSortTable()
        {
            DataTable sortTable = null, dtTemp;
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                object obj = this.dataGridView1.Rows[i].Cells[0].Value;
                string select = obj == null ? "" : obj.ToString();
                if (select == "True")
                {
                    string car_no = this.dataGridView1.Rows[i].Cells["车号"].Value.ToString();
                    string login_time = this.dataGridView1.Rows[i].Cells["登记时间"].Value.ToString();

                    string sql = "select logintime,truckno,stackname,package from TRUCK_CARGO_LOGIN where truckstatus='0' and logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "'";
                    dtTemp = db.ExecuteDataSet(db.GetSqlStringCommand(sql)).Tables[0];
                    if (sortTable == null)
                    {
                        sortTable = dtTemp;
                    }
                    else
                    {
                       sortTable.Merge(dtTemp);
                    }
                }
            }
            if (sortTable.Rows.Count > 0)//排序
            {
                sortTable.DefaultView.Sort = "logintime asc";
                sortTable = sortTable.DefaultView.ToTable();
            }
            return sortTable;
        }

        private string create_id()
        {
            string sequence = "";
            string sqlStr = "select SEQ_TRUCK.nextval from dual";
            DataSet ds1 = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr));
            if (ds1.Tables[0].Rows.Count > 0)
            {
                sequence = ds1.Tables[0].Rows[0][0].ToString();
            }
            string year_str = DateTime.Now.Year.ToString();
            string month_str = DateTime.Now.Month.ToString();
            string day_str = DateTime.Now.Day.ToString();
            string id = year_str + month_str + day_str + sequence;
            return id;
        }

        System.Timers.Timer t = new System.Timers.Timer(60000);//实例化Timer类，设置间隔时间为60秒；
        private void Dispatch_ST_Load(object sender, EventArgs e)
        {
            TruckLogin += new DataGridTruckLoginHandler(Add_DataTable);
            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件；
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件； 
            
            load_data();
        }

        void Add_DataTable(DataTable dt)
        {

            this.dataGridView1.AutoGenerateColumns = true;
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.DataSource = dt;
            //设置某些字段不可见
            this.dataGridView1.Columns["TRUCKSTATUS"].Visible = false;
            //设置checkbox 列的宽度
            this.dataGridView1.Columns["SelectFlag"].Width = 50;

            //刷新右边的关联表;
            set_detail_grid();
        }
        public void theout(object source, System.Timers.ElapsedEventArgs e)
        {
            //Begin time value
            string date_time_begin = this.dateTimePicker1.Value.ToString();
            int ind = date_time_begin.IndexOf(" ");
            string date_value_begin = date_time_begin.Substring(0, ind);
            //End time value
            string date_time_end = this.dateTimePicker2.Value.ToString();
            int ind2 = date_time_end.IndexOf(" ");
            string date_value_end = date_time_end.Substring(0, ind2);

            string sql = "select logintime as 登记时间,truckno as  车号,QDCARDNUM as 卡号,TRUCKSTATUS from TRUCK_CARGO_LOGIN" +
                " where (TRUCKSTATUS=0 or TRUCKSTATUS=1) and ioyardid=0 and trunc(logintime)<=to_date('" + date_value_end + "','yyyy-mm-dd') and trunc(logintime)>=to_date('" + date_value_begin + "','yyyy-mm-dd')" +
                "group by logintime,truckno,QDCARDNUM,TRUCKSTATUS  order by logintime desc";
            dt = db.ExecuteDataSet(db.GetSqlStringCommand(sql.ToString())).Tables[0];

            this.dataGridView1.BeginInvoke(TruckLogin, dt);
        }

        private void load_data()
        {
            //Begin time value
            string date_time_begin = this.dateTimePicker1.Value.ToString();
            int ind = date_time_begin.IndexOf(" ");
            string date_value_begin = date_time_begin.Substring(0, ind);
            //End time value
            string date_time_end = this.dateTimePicker2.Value.ToString();
            int ind2 = date_time_end.IndexOf(" ");
            string date_value_end = date_time_end.Substring(0, ind2);

            //string sql = "select * from TRUCK_LOGIN where TRUCKSTATUS=0 and ioyardid=1";
            //string sql = "select logintime as 登记时间,COMMANDTIME as 指令时间,SHIPNAME as 船名,BILL_NO as 提单号,cargoname as 货名,yard as 地点,cardadd as 发卡地点,truckno as  车号,stackname as 垛名,pieces as 件数,IOYARDID,TRUCKSTATUS from TRUCK_CARGO_LOGIN" +
            //    " where (TRUCKSTATUS=0 or TRUCKSTATUS=1) and ioyardid=0 and trunc(logintime)<=to_date('" + date_value_end + "','yyyy-mm-dd') and trunc(logintime)>=to_date('" + date_value_begin + "','yyyy-mm-dd')  order by logintime desc";

            string sql = "select logintime as 登记时间,truckno as  车号,QDCARDNUM as 卡号,TRUCKSTATUS from TRUCK_CARGO_LOGIN" +
                " where (TRUCKSTATUS=0 or TRUCKSTATUS=1) and ioyardid=0 and trunc(logintime)<=to_date('" + date_value_end + "','yyyy-mm-dd') and trunc(logintime)>=to_date('" + date_value_begin + "','yyyy-mm-dd')" +
                "group by logintime,truckno,QDCARDNUM,TRUCKSTATUS  order by logintime desc";
            dt = db.ExecuteDataSet(db.GetSqlStringCommand(sql.ToString())).Tables[0];

            this.dataGridView1.AutoGenerateColumns = true;
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.DataSource = dt;

            //设置某些字段不可见
            //this.dataGridView1.Columns["IOYARDID"].Visible = false;
            this.dataGridView1.Columns["TRUCKSTATUS"].Visible = false;
            //设置checkbox 列的宽度
            this.dataGridView1.Columns["SelectFlag"].Width = 50;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            load_data();
        }

        //private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    //Begin time value
        //    string date_time_begin = this.dateTimePicker1.Value.ToString();
        //    int ind = date_time_begin.IndexOf(" ");
        //    string date_value_begin = date_time_begin.Substring(0, ind);
        //    //End time value
        //    string date_time_end = this.dateTimePicker2.Value.ToString();
        //    int ind2 = date_time_end.IndexOf(" ");
        //    string date_value_end = date_time_end.Substring(0, ind2);

        //    string str = this.comboBox1.Text.ToString();
        //    string sql = "";
        //    if (str == "全部")
        //    {
        //        sql = "select logintime as 登记时间,COMMANDTIME as 指令时间,SHIPNAME as 船名,BILL_NO as 提单号,cargoname as 货名,yard as 地点,cardadd as 发卡地点,truckno as  车号,stackname as 垛名,pieces as 件数,IOYARDID,TRUCKSTATUS from TRUCK_CARGO_LOGIN" +
        //        " where (TRUCKSTATUS=0 or TRUCKSTATUS=1) and ioyardid=0 and trunc(logintime)<=to_date('" + date_value_end + "','yyyy-mm-dd') and trunc(logintime)>=to_date('" + date_value_begin + "','yyyy-mm-dd') order by logintime desc";
        //    }
        //    else
        //    {
        //        sql = "select logintime as 登记时间,COMMANDTIME as 指令时间,SHIPNAME as 船名,BILL_NO as 提单号,cargoname as 货名,yard as 地点,cardadd as 发卡地点,truckno as  车号,stackname as 垛名,pieces as 件数,IOYARDID,TRUCKSTATUS from TRUCK_CARGO_LOGIN" +
        //        " where (TRUCKSTATUS=0 or TRUCKSTATUS=1) and ioyardid=0  and cardadd='" + str + "' and trunc(logintime)<=to_date('" + date_value_end + "','yyyy-mm-dd') and trunc(logintime)>=to_date('" + date_value_begin + "','yyyy-mm-dd') order by logintime desc";
        //    }
        //    dt = db.ExecuteDataSet(db.GetSqlStringCommand(sql.ToString())).Tables[0];

        //    this.dataGridView1.AutoGenerateColumns = true;
        //    this.dataGridView1.AllowUserToAddRows = false;
        //    this.dataGridView1.DataSource = dt;

        //    //设置某些字段不可见
        //    this.dataGridView1.Columns["IOYARDID"].Visible = false;
        //    this.dataGridView1.Columns["TRUCKSTATUS"].Visible = false;
        //    //设置checkbox 列的宽度
        //    this.dataGridView1.Columns["SelectFlag"].Width = 50;
        //}

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow DGVRow in this.dataGridView1.Rows)
            {
                if (DGVRow != null)
                {
                    switch (DGVRow.Cells["TRUCKSTATUS"].Value as string)
                    {
                        case "1":
                            //DGVRow.Cells["SelectFlag"] = new DataGridViewTextBoxCell();
                            //DGVRow.Cells["SelectFlag"].Value = "";
                            DGVRow.DefaultCellStyle.BackColor = Color.Green;
                            break;
                        case "2":
                            DGVRow.Cells["SelectFlag"] = new DataGridViewTextBoxCell();
                            DGVRow.Cells["SelectFlag"].Value = "";
                            DGVRow.DefaultCellStyle.BackColor = Color.Fuchsia;
                            break;
                        case "3":
                            DGVRow.Cells["SelectFlag"] = new DataGridViewTextBoxCell();
                            DGVRow.Cells["SelectFlag"].Value = "";
                            DGVRow.DefaultCellStyle.BackColor = Color.Orange;
                            break;
                        case "4":
                            DGVRow.Cells["SelectFlag"] = new DataGridViewTextBoxCell();
                            DGVRow.Cells["SelectFlag"].Value = "";
                            DGVRow.DefaultCellStyle.BackColor = Color.LightSkyBlue;
                            break;
                        case "5":
                            DGVRow.Cells["SelectFlag"] = new DataGridViewTextBoxCell();
                            DGVRow.Cells["SelectFlag"].Value = "";
                            DGVRow.DefaultCellStyle.BackColor = Color.Yellow;
                            break;
                    }
                }
            }
        }

        private void button_cancel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                object obj = this.dataGridView1.Rows[i].Cells[0].Value;
                string select = obj == null ? "" : obj.ToString();
                if (select == "True")
                {
                    string car_no = this.dataGridView1.Rows[i].Cells["车号"].Value.ToString();
                    string login_time = this.dataGridView1.Rows[i].Cells["登记时间"].Value.ToString();
                    String update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=0,COMMANDTIME=sysdate where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS<>'9'";
                    db.ExecuteNonQuery(db.GetSqlStringCommand(update_sql.ToString()));
                    string sID = create_id();
                    string insert_sql = "insert into TRUCK_COMMAND_LOG(ID,TRUCKNO,YHBH,XM,XGSJ,XGNR,IOYARDID,SXFC,MODULE,SEND) " +
                        "values(" + sID + ",'" + car_no + "','" + Session.YHBH + "','" + Session.XM + "',sysdate,'理货中心取消进车指令','0','0','市提车辆调度','0')";
                    db.ExecuteNonQuery(db.GetSqlStringCommand(insert_sql));
                }
            }
            load_data();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dataGridView1.CurrentCell.ColumnIndex == 0)
            {
                //获取DataGridView中CheckBox的Cell
                DataGridViewCheckBoxCell dgvCheck = (DataGridViewCheckBoxCell)(this.dataGridView1.Rows[this.dataGridView1.CurrentCell.RowIndex].Cells[0]);
                //根据单击时，Cell的值进行处理。EditedFormattedValue和Value均可以,若单击时，CheckBox没有被勾上
                if (Convert.ToBoolean(dgvCheck.EditedFormattedValue) == false)
                {
                    //通过程序完成CheckBox是否勾上的控制
                    dgvCheck.Value = true;
                }
                //若单击时，CheckBox已经被勾上
                else
                {
                    dgvCheck.Value = false;
                }
            }

            set_detail_grid();
        }

        private void set_detail_grid()
        {
            string where_str = "";
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                object obj = this.dataGridView1.Rows[i].Cells[0].Value;
                string select = obj == null ? "" : obj.ToString();
                if (select == "True")
                {
                    string login_time = this.dataGridView1.Rows[i].Cells["登记时间"].Value.ToString();
                    string truck_no = this.dataGridView1.Rows[i].Cells["车号"].Value.ToString();
                    where_str = where_str + "(TRUCKNO='" + truck_no + "' and logintime = to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss')" + ") or ";
                }
            }
            if (where_str.Length > 0)
            {
                where_str = "where " + where_str;
                where_str = where_str.Substring(0, where_str.Length - 3);


            }
            else
            {
                where_str = "where TRUCKNO=''";
            }
            string sql = "select TRUCKNO as 车号,CARGONAME as 货名,SHIPPER_NAME as 货主代理,YARD as 地点,SHIPNAME as 船名,BILL_NO as 合同号,DRIVERPHONE as 司机电话,STANDARDS as 规格,MATERIAL as 材质,GETOWNER as 收货人 from TRUCK_CARGO_LOGIN " + where_str + " order by logintime desc";
            dt = db.ExecuteDataSet(db.GetSqlStringCommand(sql.ToString())).Tables[0];

            this.dataGridView2.AutoGenerateColumns = true;
            this.dataGridView2.AllowUserToAddRows = false;
            this.dataGridView2.DataSource = dt;
        }

        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 3)
            {
                string car_no = (string)dataGridView2.Rows[e.RowIndex].Cells["车号"].Value.ToString();
                string yard = (string)dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                String update_sql = "update TRUCK_CARGO_LOGIN set YARD='" + yard + "' where  TRUCKNO='" + car_no + "'";
                db.ExecuteNonQuery(db.GetSqlStringCommand(update_sql.ToString()));
            }
        }
    }
}
